const http = require('http')
const fs=require('fs')
const hostname = '127.0.0.1'
const port = 3000
const path=require('path')

const server = http.createServer((req, res) => {
  const url=req.url
  const ext=path.extname(url)
 
  res.statusCode = 200
  switch(ext){
    case '.html':
      res.setHeader('Content-Type', 'text/html;charset=utf-8')
      fs.createReadStream(__dirname + url,'utf8').pipe(res)
      break;
    case '.css':
      res.setHeader('Content-Type', 'text/css;charset=utf-8')
      fs.createReadStream(__dirname + url,'utf8').pipe(res)
      break;
    case '.js':
      res.setHeader('Content-Type', 'application/x-javascript')
      fs.createReadStream(__dirname + url,'utf8').pipe(res)
      break;
    default:
      res.setHeader('Content-Type', 'text/html;charset=utf-8')
      fs.createReadStream(__dirname + '/html/1.index.html','utf8').pipe(res)
  }
  console.log(url)
  let data = []
  req.on('data', chunk => {
      data.push(chunk)  // 将接收到的数据暂时保存起来
  })
  req.on('end', () => {
    if(url==="/denglu"){
    let arr=JSON.parse(data)//客服端传来的数据，是它变对象
    console.log(arr)// 数据传输完，打印数据的内容
    let re=fs.readFileSync("./js/useadd.json","utf8").toString() 
    const reuse=JSON.parse(re)
    console.log(reuse)
    reuse.forEach(item=>{
    if(item.usename===arr.usename&&item.usepwd===arr.usepwd){
      console.log("成功登陆")
      res.end("成功")
    }
   })
    }else if(url==="/zc"){
          let arr=JSON.parse(data)//客服端传来的数据，是它变对象
          console.log(arr)// 数据传输完，打印数据的内容
          let re=fs.readFileSync("./js/useadd.json","utf8").toString() 
          const reuse=JSON.parse(re)
          console.log(reuse)
          let pad=true;
          reuse.forEach(item=>{
          if(item.usename===arr.usename){
            console.log("用户存在")
            res.end("用户存在")
          }else{
            pad=false;
          }
         })
         if(pad==false){
          reuse.push(arr)
          fs.writeFileSync("./js/useadd.json",JSON.stringify(reuse))
          console.log("新用户")
         }
    }
  })
})

server.listen(port, hostname, () => {
  console.log(`服务器运行在 http://${hostname}:${port}/`)
})

